//
//  MotionManager.m
//  CIRectangleDetectDemo
//
//  Created by 黄旭 on 2023/3/3.
//  Copyright © 2023 fujikoli(李鑫). All rights reserved.
//  设备传感器实现类

#import "MotionManager.h"
#import <CoreMotion/CoreMotion.h>

@interface MotionManager ()

@property(nonatomic,strong)CMMotionManager* motionManager;
@property(nonatomic,copy)void(^motionHandler)(BOOL flatwise);

@end

@implementation MotionManager
-(void)startWithResult:(void(^)(BOOL flatwise))result{
    [self motionManager];
    self.motionHandler = result;
}
-(void)stop{
    if(_motionManager) [_motionManager stopDeviceMotionUpdates];
    _motionManager = nil;
}
-(CMMotionManager *)motionManager{
    if(!_motionManager){
        ///获取视频录制时方向
        _motionManager = [[CMMotionManager alloc] init];
        //获取间隔时间
        _motionManager.deviceMotionUpdateInterval = 0.2;
        if (_motionManager.deviceMotionAvailable) {
            __weak typeof(self) weakSelf = self;
            [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    double z = motion.gravity.z;
                    if(z <= -0.9){
                        //手机正面朝上较平放
                        if(weakSelf.motionHandler) weakSelf.motionHandler(YES);
                    }else{
                        if(weakSelf.motionHandler) weakSelf.motionHandler(NO);
                    }
                });
            }];
        } else {
            if(self.motionHandler) self.motionHandler(YES);
            //NSLog(@"No device motion on device");
        }
    }
    return _motionManager;
}
- (void)dealloc{
    [self stop];
}
@end
